#include "opencv2/opencv.hpp"

void resize_bilinear_interpolation(cv::Mat matDst1,cv::Mat matSrc)
{
    uchar* dataDst = matDst1.data;
    int stepDst = matDst1.step;
    uchar* dataSrc = matSrc.data;

    int stepSrc = matSrc.step;
    int iWidthSrc = matSrc.cols;
    int iHiehgtSrc = matSrc.rows;

    int dis_w = matDst1.cols;
    int dis_h = matDst1.rows;

    float scale_y = iHiehgtSrc/dis_h;
    float scale_x = iWidthSrc/dis_w;

    for (int j = 0; j < matDst1.rows; ++j)
    {
        float fy = (float)((j + 0.5) * scale_y - 0.5);
        int sy = cvFloor(fy);
        fy -= sy;
        sy = std::min(sy, iHiehgtSrc - 2);
        sy = std::max(0, sy);

        short cbufy[2];
        cbufy[0] = cv::saturate_cast<short>((1.f - fy) * 2048);
        cbufy[1] = 2048 - cbufy[0];

        for (int i = 0; i < matDst1.cols; ++i)
        {
            float fx = (float)((i + 0.5) * scale_x - 0.5);
            int sx = cvFloor(fx);
            fx -= sx;

            if (sx < 0) {
                fx = 0, sx = 0;
            }
            if (sx >= iWidthSrc - 1) {
                fx = 0, sx = iWidthSrc - 2;
            }

            short cbufx[2];
            cbufx[0] = cv::saturate_cast<short>((1.f - fx) * 2048);
            cbufx[1] = 2048 - cbufx[0];

            for (int k = 0; k < matSrc.channels(); ++k)
            {
                *(dataDst+ j*stepDst + 3*i + k) = (*(dataSrc + sy*stepSrc + 3*sx + k) * cbufx[0] * cbufy[0] + 
                    *(dataSrc + (sy+1)*stepSrc + 3*sx + k) * cbufx[0] * cbufy[1] + 
                    *(dataSrc + sy*stepSrc + 3*(sx+1) + k) * cbufx[1] * cbufy[0] + 
                    *(dataSrc + (sy+1)*stepSrc + 3*(sx+1) + k) * cbufx[1] * cbufy[1]) >> 22;
            }
        }
    }
    cv::imwrite("linear_1.jpg", matDst1);

    // cv::Mat matDst2;
    // cv::resize(matSrc, matDst2, matDst1.size(), 0, 0, 1);
    // cv::imwrite("linear_2.jpg", matDst);
}

int main()
{
    int dis_h=800;
    int dis_w=400;

    cv::Mat src=cv::imread("../../data/cat.png");
    printf("src h,w %d %d \n",src.rows,src.cols);

    int src_h=src.rows;
    int src_w=src.cols;
    cv::Mat dst =cv::Mat::zeros(cv::Size(dis_w,dis_h),CV_8UC3);

    resize_bilinear_interpolation(dst,src);

}